<template>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field v-model="form.name" name="姓名" label="姓名" placeholder="姓名" :rules="[{ required: true, message: '请填写姓名' }]" />
      <van-field v-model="form.tel" name="电话" label="电话" placeholder="电话" :rules="[{ required: true, message: '请填写电话' }]" />
      <van-field :modelValue="address" is-link readonly label="地区" placeholder="地区" @click="showPopup = true" :rules="[{ required: true, message: '请选择地区' }]" />
      <van-field v-model="form.detail" name="详细" label="详细" placeholder="详细" :rules="[{ required: true, message: '请填写详细地址' }]" />
    </van-cell-group>
    <div style="margin: 16px">
      <van-button round block type="primary" native-type="submit"> 添加 </van-button>
    </div>
  </van-form>
  <popup v-model:show="showPopup" v-model:provice="provice" v-model:city="city" v-model:region="region"></popup>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import popup from '@/components/popup.vue';
import { type ISelectItem } from '../../types/popup';
import { postAddressApi } from '@/api/address';
import type { IAddress } from '@/types/address';

const route = useRoute();
const router = useRouter();

const showPopup = ref(false);
const provice = ref<ISelectItem>({ value: 0, name: '' });
const city = ref<ISelectItem>({ value: 0, name: '' });
const region = ref<ISelectItem>({ value: 0, name: '' });
const address = computed(() => {
  return provice.value.name + ' ' + city.value.name + ' ' + region.value.name;
});

const form = ref<IAddress>({
  id: 0,
  name: '姓名',
  tel: '电话',
  address: '',
  code: '',
  detail: '',
});

const onSubmit = () => {
  postAddressApi({
    ...form.value,
    pname: provice.value.name,
    pid: provice.value.value,
    cname: city.value.name,
    cid: city.value.value,
    code: address.value,
    rname: region.value.name,
    rid: region.value.value,
    address: address.value + form.value.detail,
  }).then(() => {
    router.back();
  });
};
</script>

<style lang="scss" scoped></style>
